package com.stylefeng.guns.modular.pay.service.impl;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.stylefeng.guns.core.util.AjaxRes;
import com.stylefeng.guns.core.util.HttpUtils;
import com.stylefeng.guns.core.util.JsonUtils;
import com.stylefeng.guns.core.util.MD5Utils;
import com.stylefeng.guns.modular.pay.dao.TransMapper;
import com.stylefeng.guns.modular.pay.dto.TransACDTO;
import com.stylefeng.guns.modular.pay.dto.TransDTO;
import com.stylefeng.guns.modular.pay.dto.TransParams;
import com.stylefeng.guns.modular.pay.model.Trans;
import com.stylefeng.guns.modular.pay.payment.jft.common.JftConfigure;
import com.stylefeng.guns.modular.pay.payment.jft.core.AESUtil;
import com.stylefeng.guns.modular.pay.payment.jft.core.MD5Util;
import com.stylefeng.guns.modular.pay.service.ITransService;

/**
 * <p>
 * 佳付通流水表 服务实现类
 * </p>
 *
 * @author stylefeng
 * @since 2018-08-17
 */
@Service
public class TransServiceImpl extends ServiceImpl<TransMapper, Trans> implements ITransService {
    private final static Logger logger = LoggerFactory.getLogger(TransServiceImpl.class);

	@Autowired
	private TransMapper transMapper;
	@Override
	public Trans findByPlatOrderCode(String orderCode) {
		Trans trans = new Trans();
		trans.setPlatOrderCode(orderCode);
		return	transMapper.selectOne(trans);
	}
	@Override
	public List<Trans> list(Page<Trans> page, TransParams params) {
		// TODO Auto-generated method stub
		return transMapper.list(page,params);
	}
	
	@Override
	public Trans findByMchNoAndOrderCode(String mchNo, String orderCode) {
		Trans trans = new Trans();
		trans.setMchNo(mchNo);
		trans.setOrderCode(orderCode);
		return	transMapper.selectOne(trans);
	}
	
	
	@Override
	public void update(Integer id,int status, String resCode, String resMsg) {
		Trans trans = new Trans();
		trans.setId(id);
		trans.setResCode(resCode);
		trans.setResMsg(resMsg);
		transMapper.updateById(trans);
		
	}
	
	@Override
	public Trans findByOrderCode(String orderCode) {
		Trans trans = new Trans();
		trans.setOrderCode(orderCode);
		return transMapper.selectOne(trans);
		
	}
	
	@Override
	public AjaxRes orderSyn(Integer transId) {
		Trans trans = transMapper.selectById(transId);
		if(trans==null){
			return new AjaxRes("empty.trans","记录不存在");
		}
		//请求参数封装
		Map<String,String> queryMap = new HashMap<String,String>();
		queryMap.put("verCode", "1001");
		queryMap.put("chMerCode", trans.getChMerCode());
		queryMap.put("orderCode", trans.getPlatOrderCode());
		
		Map<String,String> dataMap = new HashMap<String,String>();
		String resStr = "";
		try {
			String linkString = MD5Utils.createLinkString(queryMap); 
			String sign = MD5Util.encrypt(linkString+"&md5key="+JftConfigure.MD5_KEY, "UTF-8");
			byte[] encrypt = AESUtil.encryptAES(JsonUtils.mapToJson(queryMap).getBytes(), JftConfigure.AES_KEY.getBytes(), true, "UTF-8");
			//请求
			dataMap.put("orgCode",JftConfigure.ORG_CODE);
			dataMap.put("encryptData", new String(encrypt,"UTF-8"));
			dataMap.put("signData", sign);
			resStr = HttpUtils.post(JftConfigure.BASE_URL+"/fusionPosp/interface/tradeQuery", dataMap);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		logger.info("resStr="+resStr);
		if(Strings.isNullOrEmpty(resStr)){
			return new AjaxRes("exception","系统异常");
		}
		JSONObject jsonObject = JSON.parseObject(resStr);
		if(jsonObject.containsKey("resCode")&& !"0000".equals(jsonObject.getString("resCode"))){
			String resCode = jsonObject.getString("resCode");
			String resMsg = jsonObject.getString("resMsg");
			return new AjaxRes(resCode,resMsg);
		}
		String encryptData = jsonObject.getString("encryptData");
		byte[] resDate = null;
		try {
			resDate = AESUtil.decryptAES(encryptData.getBytes(), JftConfigure.AES_KEY.getBytes(), true, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
			return new AjaxRes("exception","系统异常");
		}
		JSONObject resObject = null;
		try {
			resObject = JSON.parseObject(new String(resDate,"UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return new AjaxRes("exception","系统异常");
		}
		logger.info("resObject="+resObject.toJSONString());
		String resCode = resObject.getString("resCode");
		if("0000".equals(resCode)){
			if(trans.getTranStatus()!=0){
				update(resObject,trans.getId(),0);
			}
		}else if("0002".equals(resCode)){
			if( trans.getTranStatus()!=1){
				update(resObject,trans.getId(),1);
			}
		}else{
			if(trans.getTranStatus()!=2){
				update(resObject,trans.getId(),2);
			}
		}
		return new AjaxRes(AjaxRes.SUCCESS,"成功");
	}
	
	private void update(JSONObject resObject, Integer id, Integer status) {
		Trans updateTrans = new Trans();
		updateTrans.setId(id);
		updateTrans.setTranStatus(status);
		updateTrans.setUpdateTime(new Date());
		if(!Strings.isNullOrEmpty(resObject.getString("drawStatus"))){
			updateTrans.setDrawStatus(resObject.getInteger("drawStatus"));
		}
		if(!Strings.isNullOrEmpty(resObject.getString("drawAmount"))){
			updateTrans.setDrawAmount(resObject.getBigDecimal("drawAmount"));
		}
		if(!Strings.isNullOrEmpty(resObject.getString("resCode"))){
			updateTrans.setResCode(resObject.getString("resCode"));
		}
		if(!Strings.isNullOrEmpty(resObject.getString("resMsg"))){
			updateTrans.setResMsg(resObject.getString("resMsg"));
		}
		if(!Strings.isNullOrEmpty(resObject.getString("tranTime"))){
			updateTrans.setTranTime(resObject.getString("tranTime"));
		}
		transMapper.updateById(updateTrans);
		
	}
	/**
	 * 数据导出
	 */
	@Override
	public TransACDTO getExportData(TransParams param) {
		TransACDTO acdto = new TransACDTO();		
		List<TransDTO> details = transMapper.getExportData(param);
		for(TransDTO detail:details){
			if(detail.getSettleType().equals("0")){
				detail.setSettleType("D0");
			}
			if(detail.getTranStatus().equals("0")){
				detail.setTranStatus("交易成功");
			}else if(detail.getTranStatus().equals("1")){
				detail.setTranStatus("交易中");
			}else if(detail.getTranStatus().equals("2")){
				detail.setTranStatus("交易失败");
			}else if(detail.getTranStatus().equals("3")){
				detail.setTranStatus("待支付");
			}
		}
		acdto.setDetail(details);
		return acdto;
	}
	
	
	@Override
	public BigDecimal sumDailyAmount(String memberNo) {
		// TODO Auto-generated method stub
		return transMapper.sumDailyAmount(memberNo);
	}

	

}
